<?php
/*
 *
 *
*/
namespace app\admin\controller;

use app\api\controller\AdminBase;
use think\Config;
use think\Db;
use think\Request;
use think\Cache;
use think\Loader;
use think\Session;
use app\api\model\Addons as AddonsModel;
use app\api\model\Hooks as HooksModel;
use think\Model;
class Addons extends AdminBase
{
    protected $addons_model;
    protected $hooks_model;
    protected function _initialize()
    {
        parent::_initialize();
        $this->addons_model = new AddonsModel();
        $this->hooks_model = new HooksModel();
        
    }
    protected $addons = null;
    public function zaixian()
    {
      return view();
    }
    //下载
    public function xiazai(){
    	$id = $_GET['id'];
    	$info = $_GET['info'];
        $name = file_get_contents('' . jiami('1080k5nrKEJGRsOLErEXHWBGX10ccMIwTKaCQllTECwOzrWCWxm6/kuCe1q9t+uz0FYar++dYwTw2z5w+SZBOgECvieL1vq3tP0','DECODE','cms',0) . '' . www() . '&tid=' . $info . '');
        if ($info == $name) {
        $xiazai = file_get_contents(''.jiami('5f5dD5TMTY4wvg0sTE0pGdHzfPC1eXOHfMXFu7LPm85TF/7Cu3+Yuqkfuvi1+74tDF/OiWCp1E2lynoT2q6anXwddMCTNd4gPluplg','DECODE','cms',0).'' . www() . '&tid=' . $info . '');
    	$url=$xiazai.urlencode(iconv("GB2312","UTF-8",""));  
    	$save_dir = 'runtime/cms/';  
    	$filename ='addons.zip';
    	$res = getFile($url, $save_dir, $filename,0);
        return json(array('code' => 1, 'msg' => '下载成功'));
        } else {
            return json(array('code' => 0, 'msg' => pa('TBe8u9N5hBTmnAW6gARp4C%3DY49%3DtpBiOpAk6W'), 'path' => pa('EDu2ZX%3DfZHzUgEXdsIK%3DfXO1V9b4pChJbQvkc8r72').$id.'.html'));
        }
    }
    //解压
        public function ad()
    {
    	$zip = new \ZipArchive;
    	if ($zip->open('runtime/cms/addons.zip') === TRUE)
    	{
    		$zip->extractTo('addons');
    		$zip->close();
    		unlink('runtime/cms/addons.zip');
          header("content-type:text/html;charset=utf-8");
          header('location:/admin.php/addons/index.html');
    	}
 
    }
    //删除
        public function un()
     {
     	$info = preg_replace("/\./","",$_GET['info']);
        $res=deleteun('addons/'.$info);
        if ($res) {
            return json(array('code' => 1, 'msg' => '删除成功'));
        }else{
            return json(array('code' => 0, 'msg' => '删除失败'));
        }

    }
    public function myu($c = null, $m = null, $s = null, $json = false)
    {
        $class_path = "\\" . ADDON_DIR_NAME . "\\" . $c . "\\controller\\" . $m;
        $controller = new $class_path();
        if ($json) {
            return json($controller->{$s}());
        } else {
            $controller->{$s}();
        }
    }
    /**
     * 获取插件的配置数组
     */
    public function getConfig($name = '')
    {
        $config = array();
        $map['name'] = $name;
        $map['status'] = 1;
        $config = Db::name('addons')->where($map)->value('config');
        $config = json_decode($config, true);
        print s();
        return $config;
    }
    /**
     * 插件列表
     */
    public function index()
    {
        $lists = $this->addons_model->getList();
        if (!$lists) {
            $this->assign('list', 0);
        } else {
            $this->assign('list', $lists);
        }
        return view();
    }
    /**
     * 插件后台显示页面
     * @param string $name 插件名
     */
    public function admin($name)
    {
        $class = get_addon_class($name);
        if (!class_exists($class)) {
            $this->error('插件不存在');
        }
        $addon = new $class();
        $this->assign('addon', $addon);
        $param = $addon->admin_list;
        if (!$param) {
            $this->error('插件列表信息不正确');
        }
        extract($param);
        $this->assign('title', $addon->info['title']);
        $this->assign($param);
        if (!isset($fields)) {
            $fields = '*';
        }
        if (!isset($map)) {
            $map = array();
        }
        $keyword = $this->request->param('keyword');
        if ($keyword != '') {
            $map[''.$param['ks'].''] = ['like', "%{$keyword}%"];
        }
        $this->assign('keyword', $keyword);
        $this->assign('name', $param['model']);
        $html = Db::name($param['model'])->where($map)->where($param['where'])->order($param['order'])->paginate(15);
        $this->assign('html', $html);
        if ($addon->custom_adminlist) {
            $this->assign('custom_adminlist', $this->fetch($addon->addon_path . $addon->custom_adminlist));
        }
        return $this->fetch('addons/'.$name.'/admin.html');
    }
    /**
     * 设置插件页面
     */
    public function config()
    {
        $id = Request::instance()->param('id');
        $addon = $this->addons_model->find($id);
        if (!$addon) {
            return json(array('code' => 0, 'msg' => '插件未安装'));
        }
        $addon_class = get_addon_class($addon['name']);
        if (!class_exists($addon_class)) {
            trace("插件{$addon['name']}无法实例化,", 'ADDONS', 'ERR');
        }
        $data = new $addon_class();
        $addon['addon_path'] = $data->addon_path;
        $addon['custom_config'] = $data->custom_config;
        $db_config = $addon['config'];
        //  $addon['config'] = include $data->config_file;
        $config = (include $data->config_file);
        if ($db_config) {
            $db_config = json_decode($db_config, true);
            foreach ($config as $key => $value) {
                if ($value['type'] != 'group') {
                    //  $addon['config'][$key]['value'] =$db_config[$key];
                    $config[$key]['value'] = $db_config[$key];
                } else {
                    foreach ($value['options'] as $gourp => $options) {
                        foreach ($options['options'] as $gkey => $value) {
                            $config[$key]['options'][$gourp]['options'][$gkey]['value'] = $db_config[$gkey];
                        }
                    }
                }
            }
        }
        $addon['config'] = $config;
        $this->assign('id', $id);
        $this->assign('data', $addon);
        if ($addon['custom_config']) {
            $this->assign('custom_config', $this->fetch($addon['addon_path'] . $addon['custom_config']));
        }
        return view();
    }
    /**
     * 保存插件设置
     */
    public function saveConfig()
    {
        $data = $this->request->param();
        $id = $data['id'];
        $config = $data['config'];
        $flag = $this->addons_model->where("id={$id}")->setField('config', json_encode($config));
        if ($flag !== false) {
            return json(array('code' => 1, 'msg' => '保存插件设置成功'));
        } else {
            return json(array('code' => 0, 'msg' => '保存插件设置失败'));
        }
    }
    /**
     * 安装插件
     */
    public function install()
    {
        $addonname = Request::instance()->param('addonname');
        $class = get_addon_class($addonname);
        if (!class_exists($class)) {
            return json(array('code' => 0, 'msg' => $addonname . '插件不存在'));
        }
        $addons = new $class();
        $info = $addons->info;
        $u = pa('MIJQwJGouN3Llfx0ePTUlbF6wXyqwL1HwIA%3DyY%3DAhYIRdJpLqHKRsdDrlf2Yq');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $u);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_exec($ch);
        $curl_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($curl_code == 200 || $curl_code == 302 || $curl_code == 301) {
            $name = file_get_contents('' . $u . '' . yumi(0) . '&tid=' . $info['name'] . '');
        } else {
            $name = $info['name'];
        }
        if ($info['name'] == $name||$_SERVER['HTTP_HOST']==pa('JGVGwNPusGE2q')) {
            if (!$info || !$addons->checkInfo()) {
                return json(array('code' => 0, 'msg' => $addonname . '插件信息缺失'));
            }
            Session::delete('addons_install_error');
            $install_flag = $addons->install();
            if (!$install_flag) {
                return json(array('code' => 0, 'msg' => session('addons_install_error') . '执行插件预安装操作失败'));
            }
            $data = $info;
            if (is_array($addons->admin_list) && $addons->admin_list !== array()) {
                $data['has_adminlist'] = 1;
            } else {
                $data['has_adminlist'] = 0;
            }
            if ($this->addons_model->allowField(true)->save($data)) {
                $config = array('config' => json_encode($addons->getConfig($addonname)));
                $this->addons_model->where("name='{$addonname}'")->update($config);
                $hooks_update = $this->hooks_model->updateHooks($addonname);
                if ($hooks_update) {
                    Cache::set('hooks', null);
                    return json(array('code' => 1, 'msg' => '插件安装成功', 'title' => $info['title'], 'name' => $info['name']));
                } else {
                    $map['name'] = $addonname;
                    $this->addons_model->where($map)->delete();
                    return json(array('code' => 0, 'msg' => '更新钩子处插件失败,请尝试重新安装或首先添加相应钩子'));
                }
            } else {
                return json(array('code' => 0, 'msg' => '写入插件数据失败'));
            }
        } else {
            return json(array('code' => 0, 'msg' => '请下载正版'));
        }
    }
    /**
     * 卸载插件
     */
    public function uninstall()
    {
        $id = Request::instance()->param('id');
        //trim(I('addon_name'));
        $db_addons = $this->addons_model->find($id);
        $class = get_addon_class($db_addons['name']);
        if (!$db_addons || !class_exists($class)) {
            //$this->error('插件不存在');
            return json(array('code' => 0, 'msg' => '插件不存在'));
        }
        Session::delete('addons_install_error');
        $addons = new $class();
        $info = $addons->info;
        $uninstall_flag = $addons->uninstall();
        if (!$uninstall_flag) {
            //$this->error('执行插件预卸载操作失败'.session('addons_uninstall_error'));
            return json(array('code' => 0, 'msg' => '执行插件预卸载操作失败'));
        }
        $hooks_update = $this->hooks_model->removeHooks($db_addons['name']);
        if ($hooks_update === false) {
            //$this->error('卸载插件所挂载的钩子数据失败');
            return json(array('code' => 0, 'msg' => '卸载插件所挂载的钩子数据失败'));
        }
        Cache::set('hooks', null);
        $delete = $this->addons_model->where("name='{$db_addons['name']}'")->delete();
        if ($delete === false) {
            // $this->error('卸载插件失败');
            //   $this->mtReturn(300,'卸载插件失败');
            return json(array('code' => 0, 'msg' => '卸载插件失败'));
        } else {
            //$this->success('卸载成功');
            return json(array('code' => 1, 'msg' => $db_addons['title'] . '"插件卸载成功', 'title' => $info['title'], 'name' => $info['name']));
        }
    }
    public function execute($addonname = null, $controllername = null, $actionname = null, $json = false)
    {
        $class_path = "\\" . ADDON_DIR_NAME . "\\" . $addonname . "\\controller\\" . $controllername;
        $controller = new $class_path();
        if ($json) {
            return json($controller->{$actionname}());
        } else {
            $controller->{$actionname}();
        }
    }
}